import { Form, Input, Select } from 'antd';
import type { FC, HTMLAttributes, ReactNode } from 'react';

interface IProps extends HTMLAttributes<HTMLElement> {
  editing: boolean;
  dataIndex: string;
  title?: string;
  type?: 'select' | 'input';
  options?: Array<{
    label: string;
    value: string | number;
  }>;
  children: ReactNode;
}

const EditableCell: FC<IProps> = ({
  type = 'input',
  options,
  editing,
  dataIndex,
  children,
  ...rest
}) => {
  const readonlyNode =
    type === 'select'
      ? options?.find((item) => item.value === (children as ReactNode[])?.[1])?.label
      : children;
  const editableNode =
    type === 'select' ? (
      <Select placeholder="请选择" options={options} />
    ) : (
      <Input placeholder="请输入" />
    );

  return (
    <td {...rest}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          style={{ margin: 0 }}
          hasFeedback
          rules={[{ required: true, message: '' }]}
        >
          {editableNode}
        </Form.Item>
      ) : (
        readonlyNode
      )}
    </td>
  );
};

export default EditableCell;
